package com.pdstudio.carrecom.ui.fragment.appointment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.bean.CItem;
import com.pdstudio.carrecom.bean.CarSelectInfo;
import com.pdstudio.carrecom.bean.City;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.bean.CarType.car;
import com.pdstudio.carrecom.logger.Logger;
import com.pdstudio.carrecom.tools.JsonUtil;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.ui.activity.ActivitySelectCitys;
import com.pdstudio.carrecom.ui.activity.ActivitySelectCommon;
import com.pdstudio.carrecom.ui.activity.account.ActivityGoRegister;
import com.pdstudio.carrecom.ui.activity.appointment.ActivityAppointDrive;
import com.pdstudio.carrecom.ui.activity.appointment.ActivityAppointFix;
import com.pdstudio.carrecom.ui.activity.buy.ActivityNewCar;
import com.pdstudio.carrecom.ui.fragment.account.FragmentRegisterS2;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * 预约试驾第一步
 * 类: fragmentappointdrive1 <br>
 * 描述: TODO <br>
 * 作者: xiangzhaoyu  <br>
 * 时间: 2015-6-3 下午4:29:47
 */
public class fragmentappointdrive1 extends Fragment {
	
	private View _view;
	private Activity _context;
	private Button mNextStep;
	
	private EditText mSelectDate,mUserName,mPhone,mSuggestion;
	private TextView msBrand,msSerial,msType,ms4s;
	private int brandid,serialid,typeid,s4id;
	private ImageView mCar;
	private static final int TYPE_GET_BRANDS=111111;
	private static final int TYPE_GET_SERIALS=222222;
	private static final int TYPE_GET_TYPES=333333;
	private static final int TYPE_GET_4SS=444444;
	
	private int type=TYPE_GET_BRANDS;
	
	private List<CarSelectInfo> mDatas = new ArrayList<>();
	
	DisplayImageOptions options ;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		_view = inflater.inflate(R.layout.fragment_appoint_drive_s1new, container,false);
		_context = getActivity();
		initialView();
		return _view;
	}
	
	public void initialView(){
		options = new DisplayImageOptions.Builder()
		// .showImageOnLoading(R.drawable.ic_launcher) // 设置图片在下载期间显示的图片
				.showImageForEmptyUri(R.drawable.ic_launcher)// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.ic_launcher) // 设置图片加载/解码过程中错误时候显示的图片
				// .displayer(new FadeInBitmapDisplayer(1000)) // 渐变动画
				.handler(new Handler()) // default
				.build();
		
		mCar=(ImageView)_view.findViewById(R.id.iv_appoint_car);
		mCar.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(msBrand.getText()==null||msBrand.getText().toString().equals("")){
					UIHelper.ToastMessage(_context, "请先选择品牌");
				}else{
					if(msSerial.getText()==null||msSerial.getText().toString().equals("")){
						UIHelper.ToastMessage(_context, "请选择系列");
					}else{
						if(((ActivityAppointDrive)getActivity()).currentc==null||((ActivityAppointDrive)getActivity()).currentc.id<=0){
							UIHelper.ToastMessage(_context, "请先选择车型");
						}else{
						ActivityAppointDrive agr= (ActivityAppointDrive)_context;
						agr.CarSelectTitle=msBrand.getText().toString()+msSerial.getText().toString()+msType.getText().toString();
						agr.openFragment(new fragmentappointdrive2());}
					}
				}
			}});
		
		mUserName=(EditText)_view.findViewById(R.id.et_appoint_name);
		mPhone=(EditText)_view.findViewById(R.id.et_appoint_phone);
		mSuggestion=(EditText)_view.findViewById(R.id.more_sug5);
		
		mNextStep=(Button)_view.findViewById(R.id.btn_nextstep);
		mNextStep.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//ActivityAppointDrive agr= (ActivityAppointDrive)_context;
				//agr.openFragment(new fragmentappointdrive2());
				if(msBrand.getText()==null||msBrand.getText().toString().equals("")){
					UIHelper.ToastMessage(_context, "请先选择品牌");
				}else{
					if(msSerial.getText()==null||msSerial.getText().toString().equals("")){
						UIHelper.ToastMessage(_context, "请选择系列");
					}else{
						if(msType.getText()==null||msType.getText().toString().equals("")){
							UIHelper.ToastMessage(_context, "请先选择车型");
						}else{
							if(ms4s.getText()==null||ms4s.getText().toString().equals("")){
								UIHelper.ToastMessage(_context, "请选择4s店");
							}else{
								if(mPhone.getText()==null||mPhone.getText().toString().equals("")){
									UIHelper.ToastMessage(_context, "请填写电话");
								}else{
									
									try{
										HttpExecuteJson http = new HttpExecuteJson(_context, mSubListListener);
										RequestParams rps=new RequestParams();
										rps.addBodyParameter("uid", AppContext.getInstance().getUserId()+"");
										rps.addBodyParameter("content", StringUtils.utf8Encode(mSuggestion.getText().toString()));
										rps.addBodyParameter("brand",StringUtils.utf8Encode( msBrand.getText().toString()));
										rps.addBodyParameter("series",StringUtils.utf8Encode( msSerial.getText().toString()));
										rps.addBodyParameter("model",StringUtils.utf8Encode(msType.getText().toString()));
										rps.addBodyParameter("shopId",s4id+"");
										rps.addBodyParameter("modelId",typeid+"");
										rps.addBodyParameter("type","1");
										rps.addBodyParameter("name",StringUtils.utf8Encode(mUserName.getText().toString()));
										rps.addBodyParameter("tel",StringUtils.utf8Encode(mPhone.getText().toString()));
										rps.addBodyParameter("buyDate",mSelectDate.getText().toString());
										http.post(ServiceHelper.AppointSave, rps);
										
									}catch(Exception e){}

								}
							}
						}
					}
				}
							}});
		
		mSelectDate=(EditText)_view.findViewById(R.id.et_appoint_date);
		mSelectDate.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) { 
					 
			          AlertDialog.Builder builder = new AlertDialog.Builder(_context); 
			          View view = View.inflate(_context, R.layout.date_time_dialog, null); 
			          final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker); 
			          final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker); 
			          builder.setView(view); 
			 
			          Calendar cal = Calendar.getInstance(); 
			          cal.setTimeInMillis(System.currentTimeMillis()); 
			          datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); 
			 
			          timePicker.setIs24HourView(true); 
			          timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); 
			          timePicker.setCurrentMinute(Calendar.MINUTE); 
			 
			          if (v.getId() == R.id.et_appoint_date) { 
			              final int inType = mSelectDate.getInputType(); 
			              mSelectDate.setInputType(InputType.TYPE_NULL); 
			              mSelectDate.onTouchEvent(event); 
			              mSelectDate.setInputType(inType); 
			              mSelectDate.setSelection(mSelectDate.getText().length()); 
			                 
			              builder.setTitle("选取起始时间"); 
			              builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() { 
			 
			                  @Override 
			                  public void onClick(DialogInterface dialog, int which) { 
			 
			                      StringBuffer sb = new StringBuffer(); 
			                      sb.append(String.format("%d-%02d-%02d",  
			                              datePicker.getYear(),  
			                              datePicker.getMonth() + 1, 
			                              datePicker.getDayOfMonth())); 
			                      //sb.append("  "); 
			                      //sb.append(timePicker.getCurrentHour()) 
			                      //.append(":").append(timePicker.getCurrentMinute()); 
			 
			                      mSelectDate.setText(sb); 
			                      //etEndTime.requestFocus(); 
			                         
			                      dialog.cancel(); 
			                  } 
			              }); 
			                 
			          } 
			          //else if (v.getId() == R.id.et_end_time) { 
			          //    int inType = etEndTime.getInputType(); 
			          //    etEndTime.setInputType(InputType.TYPE_NULL);     
			          //    etEndTime.onTouchEvent(event); 
			          //    etEndTime.setInputType(inType); 
			          //    etEndTime.setSelection(etEndTime.getText().length()); 
			 
			          //    builder.setTitle("选取结束时间"); 
			          //    builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() { 
			 
			          //        @Override 
			          //        public void onClick(DialogInterface dialog, int which) { 
			 
			          //            StringBuffer sb = new StringBuffer(); 
			          //            sb.append(String.format("%d-%02d-%02d",  
			          //                    datePicker.getYear(),  
			          //                    datePicker.getMonth() + 1,  
			          //                    datePicker.getDayOfMonth())); 
			          //            sb.append("  "); 
			          //            sb.append(timePicker.getCurrentHour()) 
			          //            .append(":").append(timePicker.getCurrentMinute()); 
			          //            etEndTime.setText(sb); 
			                         
			          //            dialog.cancel(); 
			          //        } 
			          //    }); 
			          //} 
			             
			          Dialog dialog = builder.create(); 
			          dialog.show(); 
			      } 
					return true;
			}});
		
		msBrand=(TextView)_view.findViewById(R.id.et_appoint_brand);
		msBrand.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				type=TYPE_GET_BRANDS;
				getDatas(ServiceHelper.XZPP);
			}});
		
		msSerial=(TextView)_view.findViewById(R.id.et_appoint_serial);
		msSerial.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				type=TYPE_GET_SERIALS;
				getDatas(ServiceHelper.XZXL);
			}});

		msType=(TextView)_view.findViewById(R.id.et_appoint_type);
		msType.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				type=TYPE_GET_TYPES;
				getDatas(ServiceHelper.XZKX);
			}});

		ms4s=(TextView)_view.findViewById(R.id.et_appoint_4s);
		ms4s.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				type=TYPE_GET_4SS;
				getDatas(ServiceHelper.XZ4S);
			}});

		
			
	}  
	
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
           switch(requestCode){
           case TYPE_GET_BRANDS:{
        	   //UIHelper.ToastMessage(_context, ((City)data.getExtras().get("city")).toString());
        	   msBrand.setText(((CarSelectInfo)data.getExtras().get("select")).name);
        	   brandid=((CarSelectInfo)data.getExtras().get("select")).id;
        	   
        	   msSerial.setText("");
        	   serialid=0;
        	   msType.setText("");
        	   typeid=0;
        	   ImageLoader
					.getInstance()
					.displayImage(
							"",
							mCar, options);
           }break;
           case TYPE_GET_SERIALS:{
        	   //UIHelper.ToastMessage(_context, ((City)data.getExtras().get("city")).toString());
        	   msSerial.setText(((CarSelectInfo)data.getExtras().get("select")).name);
        	   serialid=((CarSelectInfo)data.getExtras().get("select")).id;
        	   
        	   msType.setText("");
        	   typeid=0;
        	   ImageLoader
					.getInstance()
					.displayImage(
							"",
							mCar, options);
           }break;
           case TYPE_GET_TYPES:{
        	   //UIHelper.ToastMessage(_context, ((City)data.getExtras().get("city")).toString());
        	   ((ActivityAppointDrive)getActivity()).currentc=(CarSelectInfo)data.getExtras().get("select");
        	   msType.setText(((CarSelectInfo)data.getExtras().get("select")).name);
        	   typeid=((CarSelectInfo)data.getExtras().get("select")).id;
        	   
   			// Logger.i(mAdUrl);
   			// TODO:传入后台传来的url
   			ImageLoader
   					.getInstance()
   					.displayImage(
   							((CarSelectInfo)data.getExtras().get("select")).url,
   							mCar, options);
           }break;
           case TYPE_GET_4SS:{
        	   //UIHelper.ToastMessage(_context, ((City)data.getExtras().get("city")).toString());
        	   ms4s.setText(((CarSelectInfo)data.getExtras().get("select")).name);
        	   s4id=((CarSelectInfo)data.getExtras().get("select")).id;
           }break;
           }  
        
    }
	
	private void getDatas(String url) {
		try {
			HttpExecuteJson http = new HttpExecuteJson(_context,
					mNewCarBoutiqueListener);
			Map<String, Object> rps = new HashMap<String, Object>();
			rps.put("os", "android");
			rps.put("size", "30-60");
			rps.put("uid", AppContext.getInstance().getUserId());
			//TODO:获取品牌id
			rps.put("brandId", brandid);
			//TODO:获取系列ID
			rps.put("seriesId", serialid);
			Logger.i(url);
			http.get(url, rps);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private httpReturnJson mNewCarBoutiqueListener = new httpReturnJson() {

		@Override
		public void onSuccess(String result) {
			Logger.json(result);
			ResultInfo resultInfo = null;
			try {
				resultInfo = new Gson().fromJson(result,
						new TypeToken<ResultInfo>() {
						}.getType());
				if ((resultInfo != null)
						&& (resultInfo.msg
								.equals(ServiceHelper.msg_code_sucess))) {
					try {
						
						mDatas = JsonUtil.fromJsonArray(
								JsonUtil.toJson(resultInfo.data),
								CarSelectInfo.class);
						
						switch (type) {
						case TYPE_GET_BRANDS:{
							//UIHelper.showSelectBrandActivity(ActivityNewCar.this, mDatas);
							type=111111;
							Intent intent = new Intent(_context, ActivitySelectCommon.class);
							intent.putExtra("title", "品牌选择");
							intent.putExtra("datas", (Serializable) mDatas);
							startActivityForResult(intent,type);
							}
							break;
						case TYPE_GET_SERIALS:{
							//UIHelper.showSelectSerialActivity(ActivityNewCar.this, mDatas);
							type=222222;
							Intent intent = new Intent(_context, ActivitySelectCommon.class);
							intent.putExtra("title", "系列选择");
							intent.putExtra("datas", (Serializable) mDatas);
							startActivityForResult(intent,type);
							}
							break;
						case TYPE_GET_TYPES:{
							//UIHelper.showSelectTypeActivity(ActivityNewCar.this, mDatas);
							type=333333;
							Intent intent = new Intent(_context, ActivitySelectCommon.class);
							intent.putExtra("title", "款型选择");
							intent.putExtra("datas", (Serializable) mDatas);
							startActivityForResult(intent,type);
							}
							break;
						case TYPE_GET_4SS:{
							//UIHelper.showSelectTypeActivity(ActivityNewCar.this, mDatas);
							type=TYPE_GET_4SS;
							Intent intent = new Intent(_context, ActivitySelectCommon.class);
							intent.putExtra("title", "4s选择");
							intent.putExtra("datas", (Serializable) mDatas);
							startActivityForResult(intent,type);
							}
							break;
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int error, String msg) {

		}

		@Override
		public void onCancel() {

		}
	};
	
	/*
	 * 提交预约
	 */
	private void DoJsonSub(String json) {
		ResultInfo edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<ResultInfo>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				UIHelper.ToastMessage(_context, "预约成功！");
				_context.finish();
			} else {
				UIHelper.ToastMessage(_context, "预约失败！"+edv.msg);

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(_context, "预约失败！"+e.getMessage());
		}
	}

	private httpReturnJson mSubListListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(_context, "预约失败！" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(_context, "预约失败！");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJsonSub(result);
		}
	};


	
}
